var config = require('./../../config').config,
    request = require('request'),
    webwx = require('./../webwx');

var webwxsendmsg = webwx.webwxsendmsg;

/**
 *
 * @param message
 * @param username
 * @returns {Promise}
 */
function tulingRet(message, username) {

    /**
     * 新闻列表处理
     * @param newsList
     * @returns {*}
     */
    function newsTypeHandle(newsList) {
        var content;
        newsList.forEach(o => {
            content.append(o.article + "\n" + "來源：" + o.source + "\n" + o.detailurl + "-------------");
        });
        return content;
    }

    var userid = username.replace('@', '');
    return new Promise((resolve, reject) => {
        var options = {
            url: config.tuling.apiUrl,
            method: 'POST',
            json: true,
            body: {
                key: config.tuling.APIkey,
                info: message,
                userid: userid
            }
        }
        console.log(options.method + "---" + options.url);
        console.log(options.body);
        request(options, (error, response, body) => {
            if (error) {
                return reject(error);
            }
            var resultContent;
            switch (body.code) {
                case 100000:
                    resultContent = body.text;
                    break;
                case 200000:
                    resultContent = body.text + "\n" + body.url;
                    break;
                case 302000:
                    resultContent = newsTypeHandle(body.list);
                    break;
                case 308000:
                    resultContent = body.text + "\n" + body.url;
                    break;
                default:
            }
            resolve(resultContent);
        });
    });
}

/**
 * 发送图灵返回的信息回去给用户
 * @param content
 * @param fromUserName
 * @param wxSession
 */
function sendWxMsgByTuling(content, fromUserName, wxSession, replyHandle) {
    tulingRet(content, fromUserName).then((data) => {
        if (typeof replyHandle == 'function') {
            replyHandle(data);
        } else {
            webwxsendmsg(data, fromUserName, wxSession);
        }
    }).catch((error) => {
        webwxsendmsg(error, fromUserName, wxSession);
    });
}


exports.tulingRet = tulingRet;
exports.sendWxMsgByTuling = sendWxMsgByTuling;